<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>vue2响应式数据的实现原理</h1>
</body>
<script>
    class Vue {
        constructor(options) {
            // console.log(options);
            // 将调用者传递的data数据挂载到实例对象上
            this.$data = options.data;

            this._proxyData();

            this._proxyMethods(options.methods);
        }
        // 实现数据劫持
        _proxyData() {
            for (let key in this.$data) {
                Object.defineProperty(this, key, {
                    get() {
                        // vue会收集数据和视图的对应关系
                        console.log(key + '被读取了');
                        return this.$data[key];
                    },
                    set(value) {
                        // 通知视图更新
                        console.log(key + '数据被修改了',value);
                        this.$data[key] = value;
                    }
                });
            }
        }
        // 代理方法
        _proxyMethods(methods){
           for(let key in methods){
                this[key]=methods[key];
           }
        }
    }
    // 创建vue实例对象
    const app = new Vue({
        data: {
            name: 'jack',
            age: 20,
            address: '中国'
        },
        methods: {
            getName() {
                console.log(this.name);
            }
        }
    });

    // console.log(app.name);
    // app.name = 'rose';
    console.log(app);
    app.getName();
</script>

</html>